package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired(required = false)
    private UserService userService;
    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        //1. 生成随机验证码
        String verifyCode = "1234";//ValidateCodeUtils.generateValidateCode(4)+"";
        log.info("本次生成的验证码："+verifyCode);
        //2. 发送信息  直接在控制台上去查看就可以了。主要是方便我们去登录，不是钱不钱问题了。
        //  SMSUtils.sendMessage("黑马旅游网","SMS_205126318",user.getPhone(),verifyCode);

        //3.  生成的验证码你需要保存到session
        //session.setAttribute("verifyCode_"+user.getPhone(),verifyCode);
        // session存储验证码转换为redis存储
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("verifyCode_"+user.getPhone(),verifyCode,1, TimeUnit.MINUTES);
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> param, HttpSession session){
        // 获取输入的手机号和验证码
        String phone = param.get("phone");
        String code = param.get("code");
        // 获取session中的验证码
        //String verifyCode = (String) session.getAttribute("verifyCode_" + phone);
        // 从redis中获取验证码
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String verifyCode = (String) valueOperations.get("verifyCode_" + phone);
        // service 校验
        User user = userService.login(phone, code, verifyCode);
        if (user != null) {
            session.setAttribute("user", user.getId());
            // redis删除缓存
            redisTemplate.delete("verifyCode_" + phone);
        }
        return R.success("登录成功");
    }
}
